package com.sinaapp.kltq.dinosaurweather;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.sinaapp.kltq.data.CityListItem;
import com.sinaapp.kltq.data.WeatherDay;
import com.sinaapp.kltq.data.WeatherRealTime;
import com.sinaapp.kltq.data.WeatherZhishu;
import com.sinaapp.kltq.weathermanager.WeatherManager;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;


/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link TitleFragment.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link TitleFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class TitleFragment extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment TitleFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static TitleFragment newInstance(String param1, String param2) {
        TitleFragment fragment = new TitleFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    public TitleFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_title, container, false);
    }

    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onStart() {
        // 如果当前是空页面
        if (getActivity().getClass() == EmptyActivity.class) {
            ((TextView) getActivity().findViewById(R.id.titleCity)).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(getActivity(), CityManagement.class);
                    getActivity().startActivity(intent);
                    getActivity().overridePendingTransition(R.anim.anim_none, R.anim.anim_none);
                }
            });
            super.onStart();
            return;
        }
        // 正常页面
        // 获取城市序号
        final int cityIndex;
        if (getActivity().getClass() == FlipWhiteActivity.class) {
            cityIndex = ((FlipWhiteActivity)getActivity()).cityIndex;
        } else {
            cityIndex = ((FlipBlackActivity)getActivity()).cityIndex;
        }
        // 显示城市名、当前日期
        WeatherManager wm = new WeatherManager(getActivity().getApplicationContext());
        final String city = wm.getCityList().get(cityIndex).city;
        ((TextView) getActivity().findViewById(R.id.titleCity)).setText(city);
        ((TextView) getActivity().findViewById(R.id.titleDate)).setText(
                new SimpleDateFormat("MM/dd E").format(new Date(System.currentTimeMillis())));
        // 分享按钮
        ((ImageView) getActivity().findViewById(R.id.titleShareBtn)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 截屏
                View view = v.getRootView();
                view.setDrawingCacheEnabled(true);
                view.buildDrawingCache();
                Bitmap bitmap = view.getDrawingCache();
                // test for save file


                // TODO: 截屏分享
//                Intent shareIntent = new Intent();
//                shareIntent.setAction(Intent.ACTION_SEND);
//                shareIntent.putExtra(Intent.EXTRA_STREAM, bitmap);
//                shareIntent.setType("image/jpeg");
//                startActivity(Intent.createChooser(shareIntent, "这条分享来自恐龙天气"));
                // 临时
                char pageType;
                if (getActivity().getClass() == FlipWhiteActivity.class) {
                    pageType = ((FlipWhiteActivity) getActivity()).pageType;
                } else {
                    pageType = ((FlipBlackActivity) getActivity()).pageType;
                }
                WeatherManager wm = new WeatherManager(getActivity().getApplicationContext());
                Intent sendIntent = new Intent();
                sendIntent.setAction(Intent.ACTION_SEND);
                sendIntent.putExtra(Intent.EXTRA_TEXT, getShareContent(city, pageType));
                sendIntent.setType("text/plain");
                startActivity(sendIntent);
            }
        });
        // 点击城市名进入城市管理
        ((TextView) getActivity().findViewById(R.id.titleCity)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                char pageType;
                if (getActivity().getClass() == FlipWhiteActivity.class) {
                    pageType = ((FlipWhiteActivity) getActivity()).pageType;
                } else {
                    pageType = ((FlipBlackActivity) getActivity()).pageType;
                }
                Intent intent = new Intent(getActivity(), CityManagement.class);
                intent.putExtra("cityIndex", cityIndex);
                intent.putExtra("pageType", pageType);
                getActivity().startActivity(intent);
                getActivity().overridePendingTransition(R.anim.anim_none, R.anim.anim_none);
                getActivity().finish();
            }
        });
        // 显示小圆点
        LinearLayout linearLayout = (LinearLayout) getActivity().findViewById(R.id.titleCircle);
        if (linearLayout.getChildCount() == 0) {
            // 值
            int otherMarginLeft = px2dp(4);
            int otherMarginTop = px2dp(6);
            int otherMarginRight = px2dp(4);
            int otherMarginBottom = px2dp(8);
            int otherSize = px2dp(5);
            int currMarginLeft = px2dp(3);
            int currMarginTop = px2dp(5);
            int currMarginRight = px2dp(3);
            int currMarginBottom = px2dp(7);
            int currSize = px2dp(7);
            // 显示小圆点
            LinearLayout.LayoutParams layoutParams;
            for (CityListItem item : wm.getCityList()) {
                if (item.city.compareTo(city) == 0) {   // 当前城市
                    TextView textView = new TextView(getActivity());
//                    textView.setBackgroundResource(R.color.button_material_dark);
                    textView.setBackgroundResource(R.drawable.my_circle_cur);
                    linearLayout.addView(textView);
                    layoutParams = (LinearLayout.LayoutParams) textView.getLayoutParams();
                    layoutParams.setMargins(currMarginLeft, currMarginTop, currMarginRight, currMarginBottom);
                    layoutParams.height = layoutParams.width = currSize;
                } else {    // 其他城市
                    TextView textView = new TextView(getActivity());
//                    textView.setBackgroundResource(R.color.button_material_light);
                    textView.setBackgroundResource(R.drawable.my_circle_oth);
                    linearLayout.addView(textView);
                    layoutParams = (LinearLayout.LayoutParams) textView.getLayoutParams();
                    layoutParams.setMargins(otherMarginLeft, otherMarginTop, otherMarginRight, otherMarginBottom);
                    layoutParams.height = layoutParams.width = otherSize;
                }

            }
        }
        super.onStart();
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (OnFragmentInteractionListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p/>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        public void onFragmentInteraction(Uri uri);
    }

    private int px2dp(int dp) {
        return (int) (dp * getActivity().getResources().getDisplayMetrics().density + 0.5f);
    }

    private String getShareContent(String city, char pageType) {
        String content = "获取失败";
        WeatherManager wm = new WeatherManager(getActivity().getApplicationContext());
        // 非今日更新
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        java.util.Date today = new Date(System.currentTimeMillis());
        if (sdf.format(today).compareTo(sdf.format(wm.getUpdateDate(city))) != 0) {
            return content;
        }
        WeatherRealTime realTime = wm.getRealTimeWeather(city);
        WeatherDay day = wm.getForecastWeather(city).get(1);
        if (realTime == null || day == null)
            return content;
        String type;
        if (today.getHours() > 8 && today.getHours() < 20) {
            type = day.dayType;
        } else {
            type = day.nightType;
        }
        content = city + "实时天气：" + type
                + "，气温" + realTime.wendu + "度，湿度" + realTime.shidu + "，"
                + realTime.fengxiang + realTime.fengli;

        return content;
    }
}
